/*
 * @Author: Smthie Smthie@qq.com
 * @Date: 2024-05-20 09:12:05
 * @LastEditors: Smthie Smthie@qq.com
 * @LastEditTime: 2024-05-25 00:31:09
 * @FilePath: \ProtocolTool\src\renderer\src\store\modules\websocket.ts
 */
import { defineStore } from 'pinia'
import { store } from '@/store'
import SockJS from 'sockjs-client/dist/sockjs'
import Stomp from 'stompjs'

const wsPath = import.meta.env.RENDERER_VITE_WS_URL

type socketType = {
  stompClient: any
  timer: string
  connectStatus: boolean
}

export const useSocketStore = defineStore({
  id: 'socket',
  state: (): socketType => ({
    stompClient: null,
    timer: '',
    connectStatus: false
  }),
  actions: {
    clearTimer() {
      clearTimeout(this.timer)
      this.timer = ''
    },
    setTimer(timer: any) {
      this.timer = timer
    },
    setStompClient(stompClient: any) {
      this.stompClient = stompClient
    },
    setConnectStatus(connectStatus: boolean) {
      this.connectStatus = connectStatus
    },
    initSocket() {
      return new Promise((resolve, reject) => {
        // 建立连接对象
        const socket = new SockJS(wsPath)
        // 获取STOMP子协议的客户端对象
        const stompClient = Stomp.over(socket)
        // 定义客户端的认证信息,按需求配置
        const headers = {
          login: 'websocket',
          passcode: 'lahmy1c'
        }
        stompClient.connect(
          headers,
          () => {
            // 重连成功后，清空定时器
            this.clearTimer()
            stompClient.debug = () => {}
            this.setStompClient(stompClient)
            this.setConnectStatus(true)
            resolve(true)
          },
          (err: any) => {
            // 连接发生错误时的处理函数
            console.log(err)
            // 设置定时器，10s重连一次
            this.setTimer(
              setTimeout(() => {
                this.initSocket()
              }, 10000)
            )
            this.setConnectStatus(false)
            reject(err)
          }
        )

        /**
         * WebSocket客户端
         *
         * 使用说明：
         * 1、WebSocket客户端通过回调函数来接收服务端消息。例如：webSocket.onmessage
         * 2、WebSocket客户端通过send方法来发送消息给服务端。例如：webSocket.send();
         *
         * 配置 WebSocket
         * WebSocket客户端 PS：URL开头表示WebSocket协议 中间是域名端口 结尾是服务端映射地址
         */
        // let webSocket = new WebSocket(/*[[${webSocketUrl}]]*/ 'ws://192.168.168.92:8082/websocket/1');
        // /**
        //  * 当服务端打开连接
        //  */
        // webSocket.onopen = (event) => {
        //     console.log('WebSocket打开连接');
        //     this.clearTimer();
        //     this.setStompClient(webSocket)
        //     this.setConnectStatus(true)
        //     resolve(true)
        // };

        // /**
        //  * 当服务端发来消息：1.广播消息 2.更新在线人数
        //  */
        // webSocket.onmessage = function (event) {

        // };

        // /**
        //  * 关闭连接
        //  */
        // webSocket.onclose = (event) => {
        //     console.log('WebSocket关闭连接');
        //     // 设置定时器，10s重连一次
        //     this.setTimer(setTimeout(() => {
        //         this.initSocket()
        //     }, 10000))
        //     this.setConnectStatus(false)
        //     reject(false)
        // };

        // webSocket.onerror = (event) => {
        //     console.log('WebSocket发生异常');
        //     // 设置定时器，10s重连一次
        //     this.setTimer(setTimeout(() => {
        //         this.initSocket()
        //     }, 10000))
        //     this.setConnectStatus(false)
        //     reject(false)
        // };
      })
    }
  }
})

export function useSocketStoreHook() {
  return useSocketStore(store)
}
